import { _decorator, BoxCollider2D, Component, Contact2DType, Director, director, find, instantiate, Label, Node, Prefab, Sprite, SpriteFrame, tween, UITransform, v3, Vec3 } from 'cc';
import { UserInfo } from './UserInfo';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('GameMgr')
export class GameMgr extends Component {
    @property(Node)
    bg: Node;

    @property(Node)
    bg1: Node;
    @property(Node)
    centerBg: Node;
    @property(Node)
    failPanel: Node;
    @property(Node)
    player: Node
    @property(Prefab)
    barrierPre: Prefab;
    @property(Prefab)
    squirrelPre: Prefab;
    @property([SpriteFrame])
    barrierSpArr:SpriteFrame[]=[];
    @property(Label)
    scoreLabel:Label;
    
    isGameIng = true;
    moveSpeed = 220;

    inLeftOrRight = 0;
    isJumpIng = false;

    private playerScore = 0;
    get PlayerScore() {
        return this.playerScore;
    }
    set PlayerScore(value) {
        this.playerScore = value;
        this.scoreLabel.string = value + "";
    }

    start() {
        this.centerBg.on(Node.EventType.TOUCH_START, this.startTouch, this);
        this.player.getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT,this.beginTouch,this)

        if (UserInfo.isAudioBgm) {
            AudioMgr.ins.play("audio/bgm")
        }

        setTimeout(()=>{
            let hei=this.bg.getChildByName("pillar").getComponent(UITransform).height;
            this.bg1.getChildByName("pillar").getComponent(UITransform).height=hei
            this.bg1.getChildByName("pillar3").getComponent(UITransform).height=hei
        },100)
      
    }

    beginTouch(self, other) {
        director.once(Director.EVENT_AFTER_PHYSICS, () => {
            if (other.tag == 20) {
                this.gameOver();
            }

        })

    }

    startTouch() {
        if (!this.isJumpIng) {
            this.isJumpIng = true;
            AudioMgr.ins.playOneShot("audio/jump");
            if (this.inLeftOrRight == 0) {
                tween(this.player)
                    .to(0.3, { position: v3(267, -100, 0) })
                    .call(() => {
                        this.inLeftOrRight = 1;
                        this.player.scale = v3(1, 1, 1)
                        this.isJumpIng = false;
                    })
                    .start()
            }
            else {
                tween(this.player)
                    .to(0.3, { position: v3(-267, -100, 0) })
                    .call(() => {
                        this.inLeftOrRight = 0;
                        this.isJumpIng = false;
                        this.player.scale = v3(-1, 1, 1)

                    })
                    .start()
            }

        }




    }

    generateSquirrelTempCount=0;
    generateSquirreTime=5;
    tempPos = v3();
    tempPos2 = v3();
    tempScoreCount=0;
    t = 0;
    update(dt: number) {
        if (this.isGameIng) {

            if (this.bg.position.y <= -1334) {
                this.bg.getPosition(this.tempPos)
                this.tempPos.y += 1334 * 2
                this.bg.setPosition(this.tempPos)
                this.generateBgEnvironment(0);
            }

            this.bg.getPosition(this.tempPos);
            this.tempPos.y -= dt * this.moveSpeed;
            this.bg.setPosition(this.tempPos)

            if (this.bg1.position.y <= -1334) {
                this.bg1.getPosition(this.tempPos2)
                this.tempPos2.y += 1334 * 2
                this.bg1.setPosition(this.tempPos2)
                this.generateBgEnvironment(1);

            }

            this.bg1.getPosition(this.tempPos2);
            this.tempPos2.y -= dt * this.moveSpeed;
            this.bg1.setPosition(this.tempPos2)
        }

        this.generateSquirrelTempCount+=dt;
        if (this.generateSquirrelTempCount>this.generateSquirreTime) {
            this.generateSquirrelTempCount=0;
            this.generateSquirrel(this.randomNum(0,1));
            this.generateSquirreTime=this.randomNum(3,10);
        }

        this.tempScoreCount+=dt;
        if (this.tempScoreCount>1) {
            this.tempScoreCount=0;
            this.PlayerScore+=1;
        }

        // this.t += dt; // 根据时间增加 t
        // this.t = Math.min(this.t, 1); // 限制 t 不超过 1

        // // 定义起点、终点和插值比例（t 范围 0-1）
        // const startPos = new Vec3(-267, -100, 0);
        // const endPos = new Vec3(267, -300, 0);
        // const currentPos = new Vec3();

        // // 线性插值：currentPos = startPos + (endPos - startPos) * t
        // Vec3.lerp(currentPos, startPos, endPos, this.t);

        // // 应用插值后的位置
        // this.player.position = currentPos;

        // // 插值完成后停止更新
        // if (this.t >= 1) {
        //     this.enabled = false;
        // }



    }

    //生成环境
    generateBgEnvironment(bgIndex) {
        if (bgIndex == 0) {
            this.bg.getChildByName("barrierRoot").removeAllChildren();

            let randNum = this.randomNum(0, 2);
            for (let i = 0; i < randNum; i++) {
                let randLR = this.randomNum(0, 1)
                let pre = instantiate(this.barrierPre);
                pre.setParent(this.bg.getChildByName("barrierRoot"));
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.barrierSpArr[this.randomNum(0, 2)]
                if (randLR == 0) {
                    pre.setPosition(-273, this.randomNum(-563, 533), 0)
                    pre.scale = v3(1, 1, 1)
                }
                else {
                    pre.setPosition(264, this.randomNum(-563, 533), 0)
                    pre.scale = v3(-1, 1, 1);
                }
            }
        }
        else {
            this.bg1.getChildByName("barrierRoot").removeAllChildren();

            console.log("bg1生成")
            let randNum = this.randomNum(0, 2);
            for (let i = 0; i < randNum; i++) {
                let randLR = this.randomNum(0, 1)
                let pre = instantiate(this.barrierPre);
                pre.setParent(this.bg1.getChildByName("barrierRoot"));
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.barrierSpArr[this.randomNum(0, 2)]
                if (randLR == 0) {
                    pre.setPosition(-273, this.randomNum(-563, 533), 0)
                    pre.scale = v3(1, 1, 1)
                }
                else {
                    pre.setPosition(264, this.randomNum(-563, 533), 0)
                    pre.scale = v3(-1, 1, 1)
                }
            }
        }
    }

    generateSquirrel(leftOrright) {
        if (leftOrright == 0) {
            let pre = instantiate(this.squirrelPre);
            pre.setParent(find("Canvas/squirrelRoot"));
            pre.setPosition(-288, 821);

            tween(pre)
            .to(4,{position:v3(-284, -828,0)})
            .call(()=>{
                pre.destroy();
            })
            .start()
        }
        else {
            let pre = instantiate(this.squirrelPre);
            pre.setParent(find("Canvas/squirrelRoot"));
            pre.setPosition(288, 821);
            pre.scale=v3(-1,1,1)

            tween(pre)
            .to(4,{position:v3(288, -828,0)})
            .call(()=>{
                pre.destroy();
            })
            .start()
        }
    }

    gameOver() {
        if (this.isGameIng) {
            this.isGameIng = false;
            AudioMgr.ins.playOneShot("audio/fail");

            console.log("游戏结束")
            this.failPanel.active = true;
            this.failPanel.getChildByName("itemBg").getChildByName("Label").getComponent(Label).string = "当前分数" + this.PlayerScore;
            if (localStorage.getItem("maxScore")) {
                this.failPanel.getChildByName("itemBg2").getChildByName("Label").getComponent(Label).string = "最高分数" + JSON.parse(localStorage.getItem("maxScore"));
            }

            if (localStorage.getItem("maxScore")) {
                let max = JSON.parse(localStorage.getItem("maxScore"));
                if (this.PlayerScore>max) {
                    localStorage.setItem("maxScore",JSON.stringify(this.PlayerScore));
                }
            }
            else{
                localStorage.setItem("maxScore",JSON.stringify(this.PlayerScore));
            }

        }


    }

    onclickHomeBtn(){
        director.loadScene("start");
    }

    onclickRestartBtn(){
        director.loadScene("main");

    }

    /**
 * @description: 包含最大值和最小值
 * @param {number} min
 * @param {number} max
 * @return {*}
 */
    randomNum(min: number, max: number) {

        let ret = Math.floor(Math.random() * (max - min + 1)) + min;

        return ret;
    }

}


